// <copyright file="UserService.cs" company="EnterpriseApi">
// Copyright (c) EnterpriseApi. All rights reserved.
// </copyright>

using EnterpriseApi.Models;
using EnterpriseApi.Repositories;

namespace EnterpriseApi.Services;

/// <summary>
/// 用户服务实现类，提供用户特有的业务逻辑操作
/// </summary>
public class UserService : Service<User>, IUserService
{
    private readonly IUserRepository _userRepository;

    /// <summary>
    /// 初始化UserService的新实例
    /// </summary>
    /// <param name="userRepository">用户仓储</param>
    public UserService(IUserRepository userRepository) : base(userRepository)
    {
        _userRepository = userRepository;
    }

    /// <summary>
    /// 根据用户名获取用户
    /// </summary>
    /// <param name="username">用户名</param>
    /// <returns>用户对象，如果不存在则返回null</returns>
    public async Task<User?> GetByUsernameAsync(string username)
    {
        return await _userRepository.GetByUsernameAsync(username);
    }

    /// <summary>
    /// 根据邮箱获取用户
    /// </summary>
    /// <param name="email">邮箱地址</param>
    /// <returns>用户对象，如果不存在则返回null</returns>
    public async Task<User?> GetByEmailAsync(string email)
    {
        return await _userRepository.GetByEmailAsync(email);
    }

    /// <summary>
    /// 注册新用户
    /// </summary>
    /// <param name="user">用户信息</param>
    /// <param name="password">用户密码</param>
    /// <returns>注册的用户</returns>
    public async Task<User> RegisterUserAsync(User user, string password)
    {
        if (user == null)
        {
            throw new ArgumentNullException(nameof(user));
        }

        if (string.IsNullOrWhiteSpace(password))
        {
            throw new ArgumentException("密码不能为空", nameof(password));
        }

        // 检查用户名是否已存在
        if (await _userRepository.IsUsernameExistsAsync(user.Username))
        {
            throw new ArgumentException($"用户名 '{user.Username}' 已存在", nameof(user.Username));
        }

        // 检查邮箱是否已存在
        if (await _userRepository.IsEmailExistsAsync(user.Email))
        {
            throw new ArgumentException($"邮箱 '{user.Email}' 已被注册", nameof(user.Email));
        }

        // 密码加密（简化版，实际应用中应使用更复杂的加密方式）
        user.PasswordHash = BCrypt.Net.BCrypt.HashPassword(password);
        user.CreatedAt = DateTime.UtcNow;
        user.UpdatedAt = null;

        return await _userRepository.AddAsync(user);
    }

    /// <summary>
    /// 验证用户凭据
    /// </summary>
    /// <param name="username">用户名</param>
    /// <param name="password">用户密码</param>
    /// <returns>验证结果和用户对象</returns>
    public async Task<(bool IsValid, User? User)> ValidateUserAsync(string username, string password)
    {
        if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
        {
            return (false, null);
        }

        var user = await _userRepository.GetByUsernameAsync(username);
        if (user == null || !user.IsActive)
        {
            return (false, null);
        }

        // 验证密码（简化版，实际应用中应使用与加密方式匹配的验证方法）
        bool isValidPassword = BCrypt.Net.BCrypt.Verify(password, user.PasswordHash);

        return (isValidPassword, isValidPassword ? user : null);
    }

    /// <summary>
    /// 获取活跃用户列表
    /// </summary>
    /// <returns>活跃用户集合</returns>
    public async Task<IEnumerable<User>> GetActiveUsersAsync()
    {
        return await _userRepository.GetActiveUsersAsync();
    }

    /// <summary>
    /// 获取特定角色的用户列表
    /// </summary>
    /// <param name="roleId">角色ID</param>
    /// <returns>特定角色的用户集合</returns>
    public async Task<IEnumerable<User>> GetUsersByRoleAsync(int roleId)
    {
        return await _userRepository.GetUsersByRoleAsync(roleId);
    }
}